import React, {Component} from 'react';
import {Text, View, Image, StatusBar, StyleSheet} from 'react-native';
import {pxToDp} from '../../../utils/stylesKits';
import {Input} from 'react-native-elements';
import validator from '../../../utils/validator';
import request from '../../../utils/request';
import {ACCOUNT_LOGIN, ACCOUNT_VALIDATEVCODE} from '../../../utils/pathMap';
import THButton from '../../../components/THButton';
import {CodeField, Cursor} from 'react-native-confirmation-code-field';
import Toast from '../../../utils/toast';

class Index extends Component {
  state = {
    // 手机号码
    phoneNumber: '13915912347',
    // 手机号码是否合法
    phoneValid: true,
    // 是否显示登录页面
    showLogin: true,
    // 验证码输入框的值
    vcodeTxt: '',
    // 倒计时按钮的文本
    btnText: '重新获取',
    // 是否在倒计时中
    isCountdowning: false,
  };
  // 登录框手机号码输入
  phoneNumberChangeText = (phoneNumber) => {
    this.setState({phoneNumber});
  };
  // 手机号码输入完成
  phoneNumberSubmitEditing = async () => {
    /**
     * 1 对手机号码的合法性做校验 - 正则
     *  1.1 不通过 提示
     * 2 将手机号码发送到后台对应的接口 -> 获取验证码 axios
     *  2.1 发送异步请求的时候 自动的显示等待框
     *  2.2 请求结果返回后 等待框自动隐藏
     *  2.3 关键词
     *   2.3.1 等待框 ？
     *   2.3.2 自动 ？ -> axios的 拦截器
     * 3 将登录页面切换成 填写验证码的界面
     * 4 开启定时器
     */
    const {phoneNumber} = this.state;
    const phoneValid = validator.validatePhone(phoneNumber);
    this.setState({phoneValid});
    if (!phoneValid) {
      // 校验失败
      return;
    }

    const res = await request.post(ACCOUNT_LOGIN, {phone: phoneNumber});
    console.log(res);
    if (res.code === '10000') {
      // 请求成功
      this.setState({showLogin: false});
      // 开启定时器
      this.countdown();
    } else {
      // 请求失败
    }
  };
  // 开启获取验证码的定时器
  countdown = () => {
    if (this.state.isCountdowning) {
      return;
    }
    this.setState({isCountdowning: true});
    let seconds = 5;
    // 重新获取(5s)
    this.setState({btnText: `重新获取(${seconds}s)`});
    let timerId = setInterval(() => {
      seconds--;
      this.setState({btnText: `重新获取(${seconds}s)`});
      if (seconds === 0) {
        clearInterval(timerId);
        this.setState({btnText: '重新获取', isCountdowning: false});
      }
    }, 1000);
  };
  // 验证码输入完毕事件
  onVcodeSubmitEditing = async () => {
    /**
     * 1 对验证码做校验 长度
     * 2 将手机号码和验证码一起发送到后台
     * 3 返回值 有 isNew
     *    isNew 为true 新用户 -> 完善个人信息的页面
     *    isNew 为false 老用户 -> 交友 - 首页
     */
    const {vcodeTxt, phoneNumber} = this.state;
    if (vcodeTxt.length !== 6) {
      Toast.message('验证码不正确', 2000, 'center');
      return;
    }

    const res = await request.post(ACCOUNT_VALIDATEVCODE, {
      phone: phoneNumber,
      vcode: vcodeTxt,
    });
    if (res.code !== '10000') {
      console.log(res);
      return;
    }
    if (res.data.isNew) {
      // 新用户 UserInfo
      this.props.navigation.navigate('UserInfo');
    } else {
      // 老用户
      alert('老用户 跳转交友页面');
    }
  };
  // 渲染登录页面
  renderLogin = () => {
    const {phoneNumber, phoneValid} = this.state;
    return (
      <View>
        {/* 标题 */}
        <View>
          <Text style={styles.loginLabel}>手机号登录注册</Text>
        </View>
        {/* 输入框 */}
        <View style={{marginTop: pxToDp(25)}}>
          <Input
            placeholder="请输入手机号码"
            maxLength={11}
            keyboardType="phone-pad"
            value={phoneNumber}
            inputStyle={styles.phoneInput}
            onChangeText={this.phoneNumberChangeText}
            errorMessage={phoneValid ? '' : '手机号码格式不正确'}
            onSubmitEditing={this.phoneNumberSubmitEditing}
            leftIcon={{
              type: 'font-awesome',
              name: 'phone',
              color: '#ccc',
              size: pxToDp(20),
            }}
          />
        </View>
        {/* 渐变按钮 */}
        <View>
          <THButton
            onPress={this.phoneNumberSubmitEditing}
            style={styles.tHButton}>
            获取验证码
          </THButton>
        </View>
      </View>
    );
  };
  // 点击重新获取按钮
  repGetVcode = () => {
    this.countdown();
  };
  // 渲染填写验证码页面
  renderVcode = () => {
    const {phoneNumber, vcodeTxt, btnText, isCountdowning} = this.state;
    return (
      <View>
        <View>
          <Text style={styles.vcodeText1}>输入6位验证码</Text>
        </View>
        <View style={{marginTop: pxToDp(10)}}>
          <Text style={styles.vcodeText2}>已发到:+86 {phoneNumber}</Text>
        </View>
        <View>
          <CodeField
            value={vcodeTxt}
            onChangeText={this.onChangeVcodeTxt}
            onSubmitEditing={this.onVcodeSubmitEditing}
            cellCount={6}
            rootStyle={styles.codeFieldRoot}
            keyboardType="number-pad"
            textContentType="oneTimeCode"
            renderCell={({index, symbol, isFocused}) => (
              <Text
                key={index}
                style={[styles.cell, isFocused && styles.focusCell]}>
                {symbol || (isFocused ? <Cursor /> : null)}
              </Text>
            )}
          />
        </View>
        <View style={{marginTop: pxToDp(10)}}>
          <THButton
            disabled={isCountdowning}
            onPress={this.repGetVcode}
            style={styles.tHButton}>
            {btnText}
          </THButton>
        </View>
      </View>
    );
  };
  // 验证码输入框的值改变事件
  onChangeVcodeTxt = (vcodeTxt) => {
    this.setState({vcodeTxt});
  };
  render() {
    const {showLogin} = this.state;
    return (
      <View>
        {/* 0.0 状态栏 开始 */}
        <StatusBar backgroundColor="transparent" translucent={true} />
        {/* 0.0 状态栏 结束 */}
        {/* 1.0 背景图片 开始 */}
        <Image
          style={styles.profileBg}
          source={require('../../../res/images/profileBackground.jpg')}
        />
        {/* 1.0 背景图片 结束 */}
        {/* 2.0 内容 开始 */}
        <View style={styles.loginContainer}>
          {/* 2.1 登录 开始 */}
          {showLogin ? this.renderLogin() : this.renderVcode()}
          {/* 2.1 登录 结束 */}
        </View>
        {/* 2.0 内容 结束 */}
      </View>
    );
  }
}

const styles = StyleSheet.create({
  profileBg: {
    width: '100%',
    height: pxToDp(220), // 单位dp
  },
  loginContainer: {
    padding: pxToDp(20),
  },
  loginLabel: {
    fontSize: pxToDp(25),
    color: '#888',
    fontWeight: 'bold',
  },
  phoneInput: {
    color: '#333',
  },
  tHButton: {
    width: '85%',
    height: pxToDp(40),
    alignSelf: 'center',
    borderRadius: pxToDp(20),
  },
  vcodeText1: {
    fontSize: pxToDp(25),
    color: '#888',
    fontWeight: 'bold',
  },
  vcodeText2: {
    color: '#888',
  },
  codeFieldRoot: {marginTop: 20},
  cell: {
    width: 40,
    height: 40,
    lineHeight: 38,
    fontSize: 24,
    borderBottomWidth: 2,
    borderColor: '#00000030',
    textAlign: 'center',
    color: '#7d53ea',
  },
  focusCell: {
    borderColor: '#7d53ea',
  },
});

export default Index;
